#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QProcess>
#include <QDebug>
#include <QThread>
#include <QSettings>
#include <windows.h>
#include "QDesktopServices"
MainWindow *mainWindow = NULL;
bool isLoop = false;

#define BAT_BASE_PATH "./"

std::string LPWSTRToUTF8(LPWSTR lpwstr)
{
    int bufferSize = WideCharToMultiByte(CP_UTF8, 0, lpwstr, -1, NULL, 0,
                                         NULL, NULL);
    char *buffer = new char[bufferSize];
    WideCharToMultiByte(CP_UTF8, 0, lpwstr, -1, buffer, bufferSize, NULL,
                        NULL);
    std::string utf8String(buffer);
    delete[] buffer;
    return utf8String;
}


static BOOL CALLBACK EnumWindowProc(HWND hWnd, LPARAM lParam)
{

    TCHAR szWindow[1024] = {0};
    ::GetWindowText(hWnd, szWindow, 1023); //获取窗口标题


    std::string name = LPWSTRToUTF8((LPWSTR)szWindow);

    //DWORD dwPID; //保存进程标识符
    //接受一个窗口句柄。dwPID保存窗口的创建者的进程标识符，GetWindowThreadProcessId返回值是该创建者的线程标识符
    //GetWindowThreadProcessId(hWnd, &dwPID);
    //打开一个已存在的进程对象,并返回进程的句柄，这就是我们要的进程句柄了
    //HANDLE hBrowser = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
    //WCHAR exePath[256];
    //memset(exePath, 0, 256);
    //获取程序的path，并保存到exePath
    //GetModuleFileNameEx(hBrowser, NULL, exePath, MAX_PATH);
    //QString strProgramName = QString::fromWCharArray(exePath);
//    QString strWindowsName = QString::fromWCharArray((wchar_t *)szWindow);
    QString strWindowsName =QString::fromLocal8Bit(szWindow);

    // 过滤在桌面打开的文件夹等
    if (strWindowsName.isEmpty() ||
        strWindowsName.contains("Default IME")) {
        return TRUE;
    }
//    qDebug() << "-------------1-----" << szWindow  <<  "sdfasd" <<   << Qt::endl;
    if(strWindowsName.contains("WhiteboardRoom")){
//        qDebug() << "------------------" << Qt::endl;
        ShowWindow(hWnd, SW_HIDE);
    }
    return TRUE;
}


//调用命令行命令而不显示命令行窗口

BOOL system_hide(char* CommandLine)

{

    SECURITY_ATTRIBUTES   sa;

    HANDLE   hRead,hWrite;



    sa.nLength   =   sizeof(SECURITY_ATTRIBUTES);

    sa.lpSecurityDescriptor   =   NULL;

    sa.bInheritHandle   =   TRUE;

    if   (!CreatePipe(&hRead,&hWrite,&sa,0))

    {

        return   FALSE;

    }



    STARTUPINFO   si;

    PROCESS_INFORMATION   pi;

    si.cb   =   sizeof(STARTUPINFO);

    GetStartupInfo(&si);

    si.hStdError   =   hWrite;

    si.hStdOutput   =   hWrite;

    si.wShowWindow   =   SW_HIDE;

    si.dwFlags   =   STARTF_USESHOWWINDOW   |   STARTF_USESTDHANDLES;

    //关键步骤，CreateProcess函数参数意义请查阅MSDN

    if   (!CreateProcess(NULL, CommandLine, NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))

    {

        return   FALSE;

    }

    CloseHandle(hWrite);



//    char   buffer[4096]   =   {0};

//    DWORD   bytesRead;

//    while(true)

//    {

//        memset(buffer,0,strlen(buffer));

//        if(ReadFile(hRead,buffer,4095,&bytesRead,NULL)==NULL)

//        break;

//        //buffer中就是执行的结果，可以保存到文本，也可以直接输出

//        //printf(buffer);//这行注释掉就可以了

//        Sleep(100);

//    }

    return   TRUE;

}


void startNginx(bool isStart){
    qDebug() << "startNginx";
    if(isStart){
        system(".\\winBat\\nginxStart.bat");
    } else {
        system(".\\winBat\\nginxStop.bat");
    }
}

void startMysql(bool isStart){
    if(isStart){
        system(".\\winBat\\mysqlStart.bat");
    } else {
        system(".\\winBat\\mysqlStop.bat");
    }
}

void startRedis(QObject *parent, bool isStart){
    if(isStart){
        system(".\\winBat\\redisStart.bat");
//        QProcess *process = new QProcess(parent);
//        process->startDetached(".\\winBat\\redisStart.bat");
//        system(".\\winBat\\redisStart.bat");
    } else {
        system(".\\winBat\\redisStop.bat");
    }
}

void startMqtt(bool isStart){
    if(isStart){
        system(".\\winBat\\emqxStart.bat");
    } else {
        system(".\\winBat\\emqxStop.bat");
    }
}

void startJava(bool isStart){
    if(isStart){
//        QSting str;
        system(".\\winBat\\javaStart.bat");
        //QProcess *process = new QProcess(NULL);
        //process->startDetached(".\\winBat\\javaStart.bat");
    } else {
        system(".\\winBat\\javaStop.bat");
    }
}

void startRoom(bool isStart){
    if(isStart){
         QDesktopServices::openUrl(QUrl::fromLocalFile(
            "C://hy2//MeetServiceStart32//WhiteboardRoom.exe"
            ));
//        system(".\\winBat\\roomStart.bat");
    } else {
        system(".\\winBat\\roomStop.bat");
    }
}

// 判断指定的exe程序是否启动进程
bool isProcessRunning(const QString& exeName)
{
    QProcess process;
    process.start("tasklist", QStringList() << "/FI" << "IMAGENAME eq " + exeName);
    process.waitForFinished();

    QString output = process.readAllStandardOutput();
    return output.contains(exeName);
}

// 线程函数
void myThreadFunction()
{
    if(mainWindow != NULL){
        mainWindow->checkProcess();
    }
}

void logMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    if(mainWindow != NULL){
        mainWindow->logShow(type, context, msg);
    }
}

void MainWindow::logShow(QtMsgType type, const QMessageLogContext &context, const QString &msg){
    // 根据日志类型设置不同的文本颜色
    QString logMessage;
    switch (type) {
    case QtDebugMsg:
        logMessage = QString("[Debug]: %1").arg(msg);
        break;
    case QtInfoMsg:
        logMessage = QString("[Info]: %1").arg(msg);
        break;
    case QtWarningMsg:
        logMessage = QString("[Warning]: %1").arg(msg);
        break;
    case QtCriticalMsg:
        logMessage = QString("[Critical]: %1").arg(msg);
        break;
    case QtFatalMsg:
        logMessage = QString("[Fatal]: %1").arg(msg);
        break;
    }

    // 在QTextEdit中添加日志消息
    mainWindow->ui->textEdit->append(logMessage);
}

void MainWindow::checkProcess(){
    QThread::sleep(1);
    if(!isProcessRunning("nginx.exe")){
        startNginx(true);
    }
    if(!isProcessRunning("redis-server.exe")){
        startRedis(this,true);
    }
    if(!isProcessRunning("meetServer.exe")){
        startMqtt(true);
        startJava(true);
    }
    if(!isProcessRunning("WhiteboardRoom.exe")){
         startRoom(true);
    }


    while(isLoop){

        if(mainWindow != NULL){


            QPalette paletteRed;
            paletteRed.setColor(QPalette::WindowText, Qt::red);
            QPalette paletteGreen;
            paletteGreen.setColor(QPalette::WindowText, Qt::green);
            if(isProcessRunning("nginx.exe")){
                mainWindow->ui->labelNginx->setPalette(paletteGreen);
                mainWindow->ui->labelNginx->setText("已启动");
            } else {
                mainWindow->ui->labelNginx->setPalette(paletteRed);
                mainWindow->ui->labelNginx->setText("未启动");
            }
            if(isProcessRunning("erl.exe")){
                mainWindow->ui->labelEmqx->setPalette(paletteGreen);
                mainWindow->ui->labelEmqx->setText("已启动");
            } else {
                mainWindow->ui->labelEmqx->setPalette(paletteRed);
                mainWindow->ui->labelEmqx->setText("未启动");
            }
            if(isProcessRunning("meetServer.exe")){
                mainWindow->ui->labelMain->setPalette(paletteGreen);
                mainWindow->ui->labelMain->setText("已启动");
            } else {
                mainWindow->ui->labelMain->setPalette(paletteRed);
                mainWindow->ui->labelMain->setText("未启动");
            }
            if(isProcessRunning("redis-server.exe")){
                mainWindow->ui->labelRedis->setPalette(paletteGreen);
                mainWindow->ui->labelRedis->setText("已启动");
            } else {
                mainWindow->ui->labelRedis->setPalette(paletteRed);
                mainWindow->ui->labelRedis->setText("未启动");
            }

            if(isProcessRunning("mysqld.exe")){
                mainWindow->ui->labelMysql->setPalette(paletteGreen);
                mainWindow->ui->labelMysql->setText("已启动");
            } else {
                mainWindow->ui->labelMysql->setPalette(paletteRed);
                mainWindow->ui->labelMysql->setText("未启动");
            }

            if(isProcessRunning("WhiteboardRoom.exe")){
                mainWindow->ui->labelRoom->setPalette(paletteGreen);
                mainWindow->ui->labelRoom->setText("已启动");
            } else {
                mainWindow->ui->labelRoom->setPalette(paletteRed);
                mainWindow->ui->labelRoom->setText("未启动");
            }
        }
        QThread::sleep(1);
        EnumWindows(EnumWindowProc, NULL);
    }
}

void regAutoStart(){
    // 获取当前程序路径
    QString appPath = QCoreApplication::applicationFilePath();
    // 创建注册表项
    QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    settings.remove("MeetServiceStart");
    settings.setValue("MeetServiceStart", appPath);
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    mainWindow = this;
    ui->setupUi(this);

    ui->pushButtonStartMysql->setEnabled(false);
    ui->pushButtonStopMysql->setEnabled(false);

//    // 创建一个日志输出重定向到QTextEdit的信号槽连接
    qInstallMessageHandler(logMessageHandler);

    regAutoStart();

    isLoop = true;
    // 将线程函数与新线程关联
    QObject::connect(&thread, &QThread::started, myThreadFunction);
    // 启动线程
    thread.start();
}

MainWindow::~MainWindow()
{
    mainWindow = NULL;
    isLoop = false;
    thread.exit(0);
    QThread::sleep(3);
    delete ui;
}



void MainWindow::on_pushButtonStartNginx_clicked()
{
    startNginx(true);
}


void MainWindow::on_pushButtonStopNginx_clicked()
{
    startNginx(false);
}


void MainWindow::on_pushButtonStartMysql_clicked()
{
    startMysql(true);
}


void MainWindow::on_pushButtonStopMysql_clicked()
{
    startMysql(false);
}


void MainWindow::on_pushButtonStartMqtt_clicked()
{
    startMqtt(true);
}


void MainWindow::on_pushButtonStopMqtt_clicked()
{
    startMqtt(false);
}


void MainWindow::on_pushButtonStartRedis_clicked()
{
    startRedis(this, true);
}


void MainWindow::on_pushButtonStopRedis_clicked()
{
    startRedis(this,false);
}


void MainWindow::on_pushButtonStartMain_clicked()
{
    startJava(true);
}


void MainWindow::on_pushButtonStopMain_clicked()
{
    startJava(false);
}


void MainWindow::on_pushButtonStartAll_clicked()
{
    startNginx(true);
    startMqtt(true);
    //    startMysql(true);
    startRedis(this,true);
    startJava(true);
    startRoom(true);
}


void MainWindow::on_pushButtonStopAll_clicked()
{
    startNginx(false);
    startMqtt(false);
    //    startMysql(true);
    startRedis(this,false);
    startJava(false);
    startRoom(false);
}


void MainWindow::on_pushButtonConfig_clicked()
{
//    QProcess *process = new QProcess(this);
//    process->startDetached("Notepad+.exe C:\\hy2\\conf\\application-local.yml");
    system("start Notepad+.exe C:\\hy2\\conf\\application-local.yml");
//    QProcess process(this);
//    process.startDetached("Notepad+.exe C:\\hy2\\conf\\application-local.yml");
}


void MainWindow::on_pushButtonDebug_clicked()
{
    system("start DebugView++.exe");
//    QProcess process(this);
//    QProcess *process = new QProcess(this);
//    process->startDetached("DebugView++.exe");
}


void MainWindow::on_pushButtonStartRoom_clicked()
{
    startRoom(true);
}


void MainWindow::on_pushButtonStopRoom_clicked()
{
    startRoom(false);
}

